/**
 * 微信公众平台开发模式(JAVA) SDK
 */
package com.shixu.express.qyweixin.weixin;

import java.util.Date;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shixu.framework.core.AppContext;
import com.shixu.framework.plugins.qyweixin.pojo.AccessToken;
import com.shixu.framework.plugins.qyweixin.pojo.JsapiTicket;
import com.shixu.framework.plugins.qyweixin.service.Menu;
import com.shixu.framework.plugins.qyweixin.service.QyUser;
import com.shixu.framework.plugins.qyweixin.util.HttpKit;
import com.shixu.framework.plugins.qyweixin.util.Tools;
import com.shixu.framework.plugins.qyweixin.util.WeixinConstant;
import com.shixu.framework.util.MapUtils;

/**
 * 微信常用的API
 *
 */
public class WeChat {
	
	private static Logger log = LoggerFactory.getLogger(WeChat.class);  
	
    /**
     * 菜单操作接口
     */
    public static final Menu menu = new Menu();
    /**
     * 用户操作接口
     */
    public static final QyUser user = new QyUser();
    
    private static AccessToken token= null;
    private static JsapiTicket ticket= null;
    

    /**
     * 获取access_token
     * @return
     * @throws Exception
     */
    public static AccessToken getAccessToken() throws Exception {
    	
    	if(token!=null && !token.isExpired()){
    		log.info("-------qy access_token 未失效-----------------");
    		log.info("----qy token----"+token.getToken()+"----isExpired:"+token.isExpired());
    		return token;
    	}
    	log.info("----qy--token----"+token);
        String corpid = AppContext.getInstance().getString("corpid");
        String corpsecret = AppContext.getInstance().getString("corpsecret");
   
        return getAccessToken(corpid, corpsecret);
    }
    
    
    /**
     * 获取access_token
     * @return
     * @throws Exception
     */
    public static AccessToken getAccessToken(String corpid,String corpsecret) throws Exception {
    	
    	log.info("----corpid:----" + corpid);
    	log.info("----corpsecret:----" + corpsecret);
    	
        String jsonStr = HttpKit.get(WeixinConstant.ACCESSTOKEN_URL.concat("?corpid=") + corpid + "&corpsecret=" + corpsecret);
        log.info("----qy--access_token_result:----"+jsonStr);
        JSONObject map = JSONObject.fromObject(jsonStr);
        
        AccessToken accessToken = new AccessToken();
		
        if(map.has("errcode")){
        	log.error("----获取qy access token失败：----"+ jsonStr);
        	return accessToken;
        }
		accessToken.setToken(map.getString("access_token"));
		accessToken.setExpiresIn(map.getInt("expires_in"));
		accessToken.setUpdateTime(new Date().getTime());
		log.info("----Qyweixin获取access_token成功，有效时长{}秒 token:{}", accessToken.getExpiresIn(), accessToken.getToken());
		token = accessToken;
        return accessToken;
    }
    
    /**
     * 获取jsapi_ticket
     * @return
     * @throws Exception
     */
    public static JsapiTicket getJsapiTicket() throws Exception {
    	
    	if(ticket!=null && !ticket.isExpired()){
    		log.info("----qy_jsapi_ticket 未失效----");
    		log.info("-----qy_ticket----"+ticket.getTicket()+"----isExpired:"+ticket.isExpired());
    		return ticket;
    	}
    	
    	String accessToken = getAccessToken().getToken();
    	
    	JsapiTicket jsapiTicket=getJsapiTicket(accessToken);
    	log.info("----qy_ticket----"+jsapiTicket.getTicket());
        return jsapiTicket;
    }
    
    
    /**
     * 获取jsapi_ticket
     * @return
     * @throws Exception
     */
    public static JsapiTicket getJsapiTicket(String accessToken) throws Exception {
    	
        String jsonStr = HttpKit.get(WeixinConstant.jsapi_ticket_url.concat(accessToken));
        log.info("----qy_jsapi_ticket_result:----"+jsonStr);
        JSONObject map = JSONObject.fromObject(jsonStr);
        
        JsapiTicket jsapiTicket = new JsapiTicket();
		
        if(MapUtils.getInteger(map, "errcode")!=0){
        	log.error("----获取qy_jsapi_ticket失败：----"+ jsonStr);
        	return jsapiTicket;
        }
        jsapiTicket.setTicket(map.getString("ticket"));
        jsapiTicket.setExpiresIn(map.getInt("expires_in"));
        jsapiTicket.setUpdateTime(new Date().getTime());
		log.info("----weixin获取qy_jsapi_ticket成功，有效时长{}秒 token:{}", jsapiTicket.getExpiresIn(), jsapiTicket.getTicket());
		ticket = jsapiTicket;
        return jsapiTicket;
    }
    
    /**
     * 签名检查
     * @param token
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static Boolean checkSignature(String token, String signature, String timestamp, String nonce) {
        return Tools.checkSignature(token, signature, timestamp, nonce);
    }
    
 
}
